package com.ynny.dao;

import com.ynny.bean.Scores;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("ScoresMapper")
public class ScoresMapperImpl implements ScoresMapper{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void addScore(Scores scores) {
        String sql = "insert into scores(number, Chinese, math, English) values(?, ?, ?, ?)";
        // 定义数组来存放SQL语句中的参数
        Object[] obj = new Object[]{
                scores.getNumber(),
                scores.getChinese(),
                scores.getMath(),
                scores.getEnglish()
        };
        // 执行SQL插入语句，返回执行添加操作的记录数
        int num = jdbcTemplate.update(sql, obj);
        if (num <= 0)
            System.out.println("插入学生成绩记录失败");
    }

    @Override
    public void updateScore(String number, String course, Double score) {
        String sql = "update scores set " + course + " = ? where number = ?";

        // 定义数组来存放SQL语句中的参数
        Object[] params = new Object[]{score, number};
        int num = jdbcTemplate.update(sql, params);
        if (num <= 0)
            System.out.println("更新学生成绩记录失败");
    }

    @Override
    public void queryScoreByName(String number) {
        String sql = "select * from scores where number = ?";
        // 创建一个BeanPropertyRowMapper对象
        org.springframework.jdbc.core.RowMapper<Scores> rowMapper = new org.springframework.jdbc.core.BeanPropertyRowMapper<>(Scores.class);
        // 执行SQL查询语句，通过rowMapper返回Score类对象
        Scores score = jdbcTemplate.queryForObject(sql, rowMapper, number);
        System.out.println(score);
    }

    @Override
    public void queryAllScore() {
        String sql = "select * from scores";
        // 创建一个BeanPropertyRowMapper对象
        org.springframework.jdbc.core.RowMapper<Scores> rowMapper = new org.springframework.jdbc.core.BeanPropertyRowMapper<>(Scores.class);
        // 执行SQL查询语句，通过rowMapper返回存放Score类的对象的List集合
        List<Scores> scores = jdbcTemplate.query(sql, rowMapper);
        for (Scores score : scores) {
            System.out.println(score);
        }
    }
}
